// 开发环境使用本地服务器，生产环境使用真实域名
const BASE_URL = __wxConfig.envVersion === 'develop' 
  ? 'http://localhost:3000/api'
  : 'https://your-production-domain.com/api';

const { getToken, clearLoginState } = require('./auth');

// 添加请求拦截器，统一处理loading
let loadingCount = 0;
const showLoading = () => {
  if (loadingCount === 0) {
    wx.showLoading({
      title: '加载中',
      mask: true
    });
  }
  loadingCount++;
};

const hideLoading = () => {
  loadingCount--;
  if (loadingCount === 0) {
    wx.hideLoading();
  }
};

// 处理请求错误
const handleRequestError = (error) => {
  if (error.statusCode === 401) {
    // token 过期，清除登录状态
    clearLoginState();
    wx.showToast({
      title: '登录已过期，请重新登录',
      icon: 'none',
      duration: 2000
    });
    // 跳转到登录页
    setTimeout(() => {
      wx.switchTab({
        url: '/pages/profile/profile'
      });
    }, 2000);
  } else {
    wx.showToast({
      title: error.data?.error || '请求失败',
      icon: 'none'
    });
  }
};

const request = (url, options = {}) => {
  const token = getToken();
  const headers = Object.assign({}, options.header || {}, token ? { Authorization: token } : {});
  
  return new Promise((resolve, reject) => {
    showLoading();
    wx.request({
      url: `${BASE_URL}${url}`,
      ...options,
      header: headers,
      success: (res) => {
        if (res.statusCode >= 200 && res.statusCode < 300) {
          resolve(res.data);
        } else {
          handleRequestError(res);
          reject(res);
        }
      },
      fail: (err) => {
        handleRequestError(err);
        reject(err);
      },
      complete: () => {
        hideLoading();
      }
    });
  });
};

const api = {
  // 获取轮播图
  getBanners: () => request('/banners'),
  
  // 获取产品列表
  getProducts: () => request('/products'),
  
  // 获取分类列表
  getCategories: () => request('/categories'),
  
  // 获取订单列表
  getOrders: (status) => request(`/orders?status=${status}`),
  
  // 创建订单
  createOrder: (data) => request('/orders', {
    method: 'POST',
    data
  }),
  
  // 更新订单状态
  updateOrder: async (id, data) => {
    showLoading();
    try {
      return await request(`/orders/${id}`, {
        method: 'PUT',
        data
      });
    } finally {
      hideLoading();
    }
  },
  
  // 取消订单
  cancelOrder: (orderId) => request(`/orders/${orderId}/cancel`, {
    method: 'POST'
  }),
  
  // 获取用户信息
  getUserInfo: () => request('/user/info'),
  
  // 更新用户信息
  updateUserInfo: (data) => request('/user/info', {
    method: 'PUT',
    data
  }),

  // 获取每周特权
  getProfilePrivileges: () => request('/profile-privileges'),

  // 获取乐享服务
  getProfileServices: () => request('/profile-services'),

  // 登录
  login: (data) => request('/login', {
    method: 'POST',
    data
  }),

  // 获取信用额度
  getCredit: () => request('/credit')
};

module.exports = api; 